var express = require('express');
var router = express.Router();
const {User} = require('../models')
const {success,failure} = require('../utils/response')

//查询当前登录用户的详细信息
router.get('/me',async function (req,res){
    try {
        const user = await getUser(req)
        success(res,'查询当前用户成功',{user})
    } catch (error) {  
        failure(res,error)
    }
})


//修改当前登陆的用户的详细信息
router.put('/info',async function(req,res){
    try {
        const body = {
            nickname:req.body.nickname,
            company:req.body.company,
            avatar:req.body.avatar,
            introduce:req.body.introduce,
            sex:req.body.sex,
        }
        const user = await getUser(req)
        console.log(user);
        
        await user.update(body)
        success(res,'更新用户信息成功',{user})
    } catch (error) {
        failure(res,error)
    }
})


async function getUser(req){
    const id = req.userId
    const condition = {
        attributes:{exclude:['password']}
    }
    const user = await User.findByPk(id,condition)
    if(!user){
        throw new NotFoundError(`Id为${id}的用户未找到`)
    }
    return user
}

module.exports = router